/*
 * @Author: 冯向博
 * @Date: 2021-10-21 16:43:01
 * @LastEditTime: 2021-10-22 15:44:43
 */
const install = (Vue, vm) => {
  /**
   * 是否登录
   */
  const isLogin = () => {
    const token = vm.vuex_token;
    if (!token) {
      // 来自那个页面
      const currentPage = getCurrentPages().pop();

      const { options, route } = currentPage;
      const optionsKeys = Object.keys(options);
      let params = "";
      if (optionsKeys.length !== 0) {
        params = optionsKeys
          .reduce((pre, current) => {
            return `${pre}${current}=${options[current]}&`;
          }, "?")
          .slice(0, -1);
      }

      uni.setStorageSync("back_url", route + params);

      console.log(route);

      vm.$u.toast("请登录");
      setTimeout(() => {
        vm.$u.route({
          type: "redirect",
          url: "pages/auth/login",
        });
      }, 1500);
      return false;
    }
    return true;
  }

  /**
   * 更新用户信息
   */

  const updateUser = async () => {
    // 请求用户信息
    const userInfo = await vm.$u.api.userInfo();

    // 缓存 用户信息
    vm.$u.vuex("vuex_user", userInfo);
  }

  vm.$u.utils = {
    isLogin,
    updateUser
  }
}

export default {
  install
}